/**
 * LY.com Inc.
 * Copyright (c) 2004-2018 All Rights Reserved.
 */
package com.gitee.kamismile.stoneEureka.server.route;

import com.gitee.kamismile.gatewayAgent.common.APPChannel;
import com.gitee.kamismile.gatewayAgent.protobuf.Message;
import com.gitee.kamismile.gatewayAgent.server.bootstrap.GatewayAgentConstant;
import com.gitee.kamismile.stone.commmon.util.ValueUtils;
import com.gitee.kamismile.stoneEureka.server.GatewayConstant;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author dong.li
 * @version $Id: RouteEventHandler, v 0.1 2018/10/18 14:43 dong.li Exp $
 */
@Component
public class RouteEventHandler {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    GatewayConstant gatewayConstant;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private GatewayAgentConstant gatewayAgentConstant;


    @Autowired
    @Lazy
    RedisRouteDefinitionRepository redisRouteDefinitionRepository;

    @PostConstruct
    public void initSubscriber() {
        if(Objects.isNull(gatewayConstant.getAppRouteNotify())){
            return;
        }

        this.redisTemplate.execute((connection) -> {
            connection.subscribe((message, bytes) -> {
                logger.info("receive notify msg!");
                redisRouteDefinitionRepository.getRoutes().clear();
                sendSynVersionMessage();
            }, gatewayConstant.getAppRouteNotify().getBytes());
            return null;
        }, true);
    }

    private void sendSynVersionMessage() {
        Message.RouterMessage.Builder msg = Message.RouterMessage.newBuilder();
        Message.RouterResponse.Builder resp = Message.RouterResponse.newBuilder();
        resp.setSeq(ValueUtils.isLongNull(0));
        resp.setRouter(this.gatewayAgentConstant.getRouter());
        Message.Command.Builder cmd = Message.Command.newBuilder();
        cmd.setCommand(ValueUtils.isStringNull("app@vertx@sync"));
        resp.setCmd(cmd);
        Message.Result.Builder result = Message.Result.newBuilder();
        result.setCode(1);
        resp.setResult(result);
        msg.addResponse(resp);
        APPChannel.channels.writeAndFlush(msg);
    }
}
